package ar.uba.fi.posgrado.academy.web.action.course;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.academy.service.CourseService;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.model.Student;
import ar.uba.fi.posgrado.economy.service.CustomerService;
import ar.uba.fi.posgrado.common.service.StudentService;
import ar.uba.fi.posgrado.economy.model.Customer;
import ar.uba.fi.posgrado.economy.service.DebtService;

/**
 * Inscribe un {@link Student alumno} en un {@link Course curso}
 * 
 * @author ariel.piechotka
 * 
 */
public class EnrollStudentAction extends Action {
	/** Logger */
	private static Logger logger = Logger.getLogger(EnrollStudentAction.class);

	private CourseService courseService;

	private StudentService studentService;

	private DebtService debtService;

	private CustomerService customerService;

	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public void setDebtService(DebtService debtService) {
		this.debtService = debtService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	/**
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("Por inscribir alumno en curso ...");
		}

		Student student = studentService.getById(Long.parseLong(request
				.getParameter("idStudent")));
		Course course = courseService.getById(Long.parseLong(request
				.getParameter("idCourse")));
		Customer customer = customerService.getById(Long.parseLong(request
				.getParameter("idCustomer")));
		boolean alreadyEnrolled = course.getStudents().contains(student);
		course.getStudents().add(student);

		if (!alreadyEnrolled) {
			try {
				course = courseService.update(course);
			} catch (RepeatedNameException e) {
				logger.info(e.getMessage());
				ActionMessages errors = new ActionMessages();
				errors.add("course.code", new ActionMessage(e.getMessage(),
						false));
				saveErrors(request, errors);
				return mapping.getInputForward();
			}

			try {
				// Se intentan crear las deudas automaticamente
				this.debtService.createDebts(student, course, customer);
			} catch (PosgradoException e) {
				// Solo se loggea pero no falla
				logger
						.warn(
								"Excepcion creando las deudas auto generadas. Excepcion: ",
								e);
			}

			logger.info("Inscribir en curso finalizado");
		} else
			logger.info("El alumno ya estaba inscripto");
		return mapping.findForward("success");
	}
}
